<template>
  <div class="chart" id="NumberChart"></div>
</template>

<script>
import * as echarts from "echarts";
var NumberChart;
export default {
  name: "FlightNumberChart",
  props: ["flights"],
  data() {
    return {
      option: {
        title: {
          text: "航班分布",
          left: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          left: "left",
          data: [],
          itemStyle: {}
        },
        series: [
          {
            name: "航班数",
            type: "pie",
            radius: "70%",
            center: ["50%", "60%"],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      }
    };
  },
  methods: {
    // 计算图例
    flightNames(flights) {
      var data = [];
      for (let flight of flights) {
        if (data.indexOf(flight.flightName) == -1) {
          data.push(flight.flightName);
        }
      }
      return data;
    },
    // 计算数据
    flightData(names, flights) {
      var data = [];
      for (let fname of names) {
        data.push({
          value: 0,
          name: fname
        });
      }
      for (let flight of flights) {
        var pos = names.indexOf(flight.flightName);
        data[pos].value++;
      }
      return data;
    }
  },
  computed: {},
  watch: {
    flights: function(newval, oldval) {
      NumberChart.showLoading();
      var names = this.flightNames(newval);
      var data = this.flightData(names, newval);
      this.option.series[0].data = data;
      this.option.legend.data = names;
      NumberChart.hideLoading();
      NumberChart.setOption(this.option);
    }
  },
  mounted() {
    NumberChart = echarts.init(document.getElementById("NumberChart"));
  }
};
</script>

<style scoped>
.chart {
  width: 600px;
  height: 400px;
}
</style>